<template>
  <a-modal wrapClassName="jsonWrap" width="40%" title="JSON数据" :visible="show" @cancel="cancel">
    <codemirror class="jsonWrap_data" ref="myEditor" :value="jsonData"></codemirror>
    <div slot="footer" class="jsonWrap_button">
      <a-button
        @click="handleCopyJson"
        type="primary"
        class="copy-btn"
        data-clipboard-action="copy"
        :data-clipboard-text="jsonData"
      >
        复制数据
      </a-button>
      <a-button type="info" @click="cancel">关闭</a-button>
    </div>
  </a-modal>
</template>

<script>
import Clipboard from 'clipboard'
import { codemirror } from 'vue-codemirror-lite'
export default {
  data() {
    return {
      jsonData: '',
      show: false // 弹窗的显示与隐藏
    }
  },
  components: {
    codemirror
  },
  methods: {
    // 初始化
    init(json) {
      this.jsonData = JSON.stringify(json, null, '\t')
      this.show = true
    },
    // 复制数据
    handleCopyJson() {
      const clipboard = new Clipboard('.copy-btn')
      clipboard.on('success', () => {
        this.$message.success('复制成功')
      })
      clipboard.on('error', () => {
        this.$message.error('复制失败')
      })
      setTimeout(() => {
        // 销毁实例
        clipboard.destroy()
      }, 122)
    },
    // 关闭弹窗
    cancel() {
      this.show = false
    }
  }
}
</script>

<style lang="less" scoped>
.jsonWrap_data {
  height: 600px;

  /deep/.CodeMirror {
    height: 100%;
  }
}

.jsonWrap_button {
  text-align: center;
}
</style>
